var ReservationsRecordTable = {
    id: "ReservationsRecordTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

function _formatter(value, row, index) {
    if (row.status == "到店") {
        return '<span style="color: green" title="' + value + '">' + value + '</span>'
    } else {
        return '<span title="' + value + '">' + value + '</span>'
    }
}

function _formatterTime(value, row, index) {
    if (row.status == "到店") {
        return "<span style='color: green'>" + value.substring(0, 19) + "</span>"
    } else {
        return value.substring(0, 19);
    }
}

function _formatterTitle(value, row, index) {
    if (row.huifang === "" || row.huifang == null) {
        row.huifang = "无回访详情";
    } else {
        row.huifang = ",<b>" + "回访详情：" + row.huifang.replace(/\s{2,}/g, "");
        var reg = /,<b>/g;
        var regs = /<\/b>/g;
        row.huifang = row.huifang.replace(reg, '&#10;');
        row.huifang = row.huifang.replace(regs, ' ');
    }
    if (row.status === "到店") {
        return "<span style='color: green;cursor:pointer' title='" + row.huifang + "'>" + value.substring(0, 19) + "</span>"
    } else {
        return "<span style=' cursor:pointer' title='" + row.huifang + "' onclick='ReservationsRecordTable.reservationsNotDetail(" + '"' + row.id + '"' + ")'>" + value.substring(0, 19) + "</span>"
    }
}

ReservationsRecordTable.initColumn = function () {
    var columns = [
        {field: 'selectItem', checkbox: true},
        {title: 'phones', field: 'phones', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'customerSexHead ', visible: false, align: 'center', valign: 'middle'},
        {title: 'deptAddress', field: 'deptAddress', visible: false, align: 'center', valign: 'middle'},
        {title: 'transportation', field: 'transportation', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'id', visible: false, align: 'center', valign: 'middle',
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '预约号', field: 'reservationsNum', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {
            title: '姓名', field: 'customerName', valign: 'middle', align: 'center', sortable: true, width: 120,
            formatter: function (value, row, index) {
                if (row.status === "到店") {
                    return "<a href='javascript:;' style='color: green;display: flex;align-items: center;' onclick = 'ReservationsRecordTable.reservationsArrives(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                } else {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' onclick = 'ReservationsRecordTable.reservationsNotDetail(" + '"' + row.id + '"' + ")' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                }
            }
        },
        {title: '手机号码', field: 'customerPhone', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '手机号码2', field: 'customerPhone2', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: 'E看牙病历号', field: 'ekyNumber', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '预约门诊', field: 'outpatientName', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '到店状态', field: 'status', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '回访状态', field: 'statuss', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '预约时间', field: 'appointmentTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTitle(value, row, index);
            }
        },
        {title: '初诊时间', field: 'firstVisitDate', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '建档人', field: 'archiving', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '跟进人', field: 'follower', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '建档时间', field: 'filingTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '一级渠道', field: 'oneChannel', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '二级渠道', field: 'twoChannel', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '三级渠道', field: 'thrChannel', align: 'center', valign: 'middle', sortable: true, width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '回访', field: 'huifang', align: 'center', valign: 'middle', sortable: true, width: 250,
            formatter: function (value, row, index) {
                return '<span title="'+value+'">'+value+'</span>'
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow":"hidden","white-space":"nowrap","text-overflow":"ellipsis"}}
            }
        },
        {title: '性别', field: 'customerSex', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                var sexValue = value === 1 ? '男' : value === 2 ? '女' : '未知';
                if (row.status === "到店") {
                    return "<span style='color: green'>" + sexValue + "</span>"
                } else {
                    return sexValue;
                }
            }
        },
        {title: '年龄', field: 'customerAge', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {
            title: '开单状态', field: 'dealStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if(row.status === "到店"){
                    if (value === "已结账") {
                        return "<a href='javascript:;' style='color: green' onclick='ReservationsRecordTable.opendealStatus(" + '"' + row.id + '"' + ")'>[已结账]</a>"
                    } else {
                        return "<span style='color: green'>" + value + "</span>"
                    }
                }else {
                    return "<span>" + value + "</span>"
                }
            }
        },
        {title: '预约病种', field: 'appointmentPayService', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow":"hidden","white-space":"nowrap","text-overflow":"ellipsis"}}
            }
        },
        {title: '访问病种', field: 'accessDisease', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '关键词', field: 'keyWord', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '微信号', field: 'wechatNumber', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '备注', field: 'remarks', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow":"hidden","white-space":"nowrap","text-overflow":"ellipsis"}}
            }
        }
    ];
    return columns;
};

ReservationsRecordTable.search = function () { // 查询预约客户列表
    ReservationsRecordTable.table.refresh({query: ReservationsRecordTable.formParams()});
    // ReservationsRecordTable.tongji();
};

ReservationsRecordTable.close = function () { // 关闭窗口
    parent.layer.close(parent.layer.getFrameIndex(window.name));
};

ReservationsRecordTable.formParams = function () { // 市场预约表单查询提交参数
    var queryData = {};
    queryData['outpatientName'] = multipleSelection($('#outpatientName').val());
    queryData['area'] = $("#area").val();
    queryData['department'] = $("#department").val(); //  部门
    queryData['reach'] = $("#marketInputPublic", parent.document).val();  //姓名   电话   微信  预约号
    queryData['appointmentPayService'] = $("#appointmentPayService").val();  //预约项目
    queryData['archiving'] = $("#archiving").val();   //建档人
    queryData['follower'] = $("#follower").val();   //跟进人
    queryData['accessDisease'] = $("#accessDisease").val();  //访问病种
    queryData['oneChannel'] = $("#oneChannel").val();  //一级渠道
    queryData['twoChannel'] = $("#twoChannel").val();    //二级渠道
    queryData['thrChannel'] = $("#thrChannel").val();    //三级渠道
    queryData['statuss'] = multipleSelection($('#statuss').val());
    queryData['status'] = $("#status").val();   //状态
    queryData['startFilingTime'] = $("#startFilingTime").val();  //建档时间
    queryData['endFilingTime'] = $("#endFilingTime").val();
    return queryData;
};

// 把对象拼接成URL的键值对参数 param1=value1&param2=value2
var parseParam = function (param) {
    var paramStr = "";
    $.each(param, function (i) {
        paramStr += '&' + getSingleData(param, i);
    });
    return paramStr.substr(1);
};
var getSingleData = function (param, key) {
    return key + "=" + param[key];
};

ReservationsRecordTable.upload =function () {
    var index = layer.open({
        type: 2,
        title: '导入',
        area: ['70%', '80%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservation/reservation_import'
    });
    this.layerIndex = index;
}

ReservationsRecordTable.check = function () { // 检查是否选中
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        ReservationsRecordTable.seItem = selected[0];
        return true;
    }
};

// ReservationsRecordTable.tongji = function () { // 统计建档人数
//     var date = new Date();
//     var currentWeek = date.getDay();
//     var stepSunDay = -currentWeek + 1;
//     if (currentWeek == 0) {stepSunDay = -7;}
//     var stepMonday = 7 - currentWeek;
//     var time = date.getTime();
//     var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
//     var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
//     //发送ajax请求后台查询统计信息，赋值到对应的地方
//     var params = {
//         param1:multipleSelection($('#outpatientName').val()),
//         param2:$("#department").val(),
//         param3:$("#appointmentPayService").val(),
//         param4:$("#archiving").val(),
//         param5:$("#follower").val(),
//         param6:$("#accessDisease").val(),
//         param7:$("#oneChannel").val(),
//         param8:$("#twoChannel").val(),
//         param9:$("#thrChannel").val(),
//         param10:multipleSelection($('#statuss').val()),
//         param11:$("#status").val(),
//         param12:setDateTime(monday,0) + " " + "00:00:00",
//         param13:setDateTime(sunday,0) + " " + "23:59:59",
//         param14:$("#area").val(),
//         param15:$("#marketInputPublic", parent.document).val()
//     };
//     $.get(Feng.ctxPath + "/reservation/tongji", params ,function (data) {
//         $("#dengjiToday").html(data[0].countNum);
//         $("#dengjiYesterday").html(data[1].countNum);
//         $("#dengjiThisWeek").html(data[2].countNum);
//         $("#dengjiMonth").html(data[3].countNum);
//         $("#dengjiLastMonth").html(data[4].countNum);
//     }, "json");
// };

ReservationsRecordTable.getFollower = function () { // 选择跟进人
    var index = layer.open({
        type: 2,
        title: '添加跟进人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservations/to_follower'
    });
    this.layerIndex = index;
};

ReservationsRecordTable.getArchiving = function () { // 选择建档人
    var index = layer.open({
        type: 2,
        title: '选择建档人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservation/to_archiving'
    });
    this.layerIndex = index;
};

ReservationsRecordTable.getData = function () { // 片区筛选
    var params = {area:$("#area").val()};
    $.post(Feng.ctxPath + "/dept/getListByArea", params ,function (data) {
        $('#outpatientName').empty();
        for (var i = 0; i < data.length; i++) {
            $('#outpatientName').append("<option value=" + data[i].simplename + ">" + data[i].simplename + "</option>");
        }
        $('#outpatientName').selectpicker('refresh');
        $('#outpatientName').selectpicker('render');
        ReservationsRecordTable.search();
    }, "json");
};

ReservationsRecordTable.lightenUp = function () { // E看牙病历号点亮
    if(this.check()){
        var id = ReservationsRecordTable.seItem.id;
        var status = ReservationsRecordTable.seItem.status;
        if(status=="到店"){
            alert("此患者已到店！");
            return;
        }
        var index = layer.open({
            type: 2,
            title: '病历号点亮',
            area: ['35%', '45%'], //宽高
            fix: true, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/reservationsNotArrive/reservations_lightenUp/' + id
        });
        this.layerIndex = index;
    }
};




ReservationsRecordTable.shortMessage = function () { // 跳转到发送短信
    var dataList  = [];
    var numberList = $("#ReservationsRecordTable").bootstrapTable('getSelections');
    for (var i = 0; i < numberList.length; i++) {
        var obj = {
            id:numberList[i].id,
            customerName:numberList[i].customerName,
            customerPhone:numberList[i].customerPhone,
            appointmentTime:numberList[i].appointmentTime.substring(0, 19),
            outpatientName:numberList[i].outpatientName,
            deptAddress:numberList[i].deptAddress,
            phones:numberList[i].phones,
            transportation:numberList[i].transportation
        };
        dataList.push(obj);
    }
    sessionStorage.setItem("dataList", JSON.stringify(dataList));
    if (this.check()) {
        var id = ReservationsRecordTable.seItem.id;
        var index = layer.open({
            type: 2,
            title: '发送消息',
            area: ['60%', '80%'], //宽高
            fix: true, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/msgSend/to_market_msgSend2/' + id
        });
        this.layerIndex = index;
    }
};

ReservationsRecordTable.msgSend = function () { // 短信发送
    var dataList = JSON.parse(sessionStorage.getItem("dataList"));
    var messageData = {
        messageContent:$('#message_content').val(),
        templateCode:$("#templateCodeValue").val(),
        smsParameterId:$("#smsParameterId").val(),
        patientList:dataList
    };
    if($("#message_content").val() == ""){
        Feng.error("请选择短信模板");
        return ;
    }
    $.ajax({
        url: Feng.ctxPath + "/msgSend/msgMarketSend2",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(messageData),
        success: function (data) {
            Feng.success('操作成功!');
            ReservationsRecordTable.close();
        },
        error: function (data) {
            alert('没有权限，请联系管理员!');
        }
    });
};

ReservationsRecordTable.reservationsArrives = function (id) { // 点击表格姓名进入详情 - 已到
    var index = layer.open({
        type: 2,
        title: '到店客户详情',
        area: ['60%', '100%'], //宽高
        fix: true, //不固定
        maxmin: true,
        offset: ['0px', '40%'],
        content: Feng.ctxPath + '/reservationsArrive/reservations_arrives/' + id
    });
    this.layerIndex = index;
};

ReservationsRecordTable.reservationsNotDetail = function (id) { // 点击表格姓名进入详情 - 未到
    var pageType = $("#pageType").val();
    window.localStorage.setItem("c", pageType);
    var index = layer.open({
        type: 2,
        title: '预约客户详情',
        area: ['60%', '100%'], //宽高
        fix: true, //不固定
        maxmin: true,
        offset: ['0px', '40%'],
        content: Feng.ctxPath + '/reservationsNotArrive/to_reservationsNotDetail/' + id
    });
    this.layerIndex = index;
};

ReservationsRecordTable.addToReservations = function () { // 新建
    var index = layer.open({
        type: 2,
        title: '添加预约客户',
        area: ['65%', '100%'], //宽高
        fix: true, //不固定
        maxmin: true,
        offset: ['0px', '15%'],
        content: Feng.ctxPath + '/reservation/reservations_addTo'
    });
    this.layerIndex = index;
};

ReservationsRecordTable.resetSearch = function () { // 重置
    $("#marketInputPublic", parent.document).val("");
    $("#archiving").val("");
    $("#follower").val("");
    $("#accessDisease").val("");
    $("#status").val("");
    $("#appointmentPayService").val("");
    $("#statuss").selectpicker('deselectAll');
    $("#oneChannel").val("请选择");
    $("#twoChannel").val("请选择");
    $("#thrChannel").val("请选择");
    $("#outpatientName").selectpicker('deselectAll');
    $("#area").val("");
    $("#department").val("");
    $("#startFilingTime").val("");
    $("#endFilingTime").val("");
    ReservationsRecordTable.search();
};

ReservationsRecordTable.reservationsExport = function () { // 导出
    var param = parseParam(ReservationsRecordTable.formParams());
    location.href = Feng.ctxPath + '/reservation/reservationsExportJD?' + param;
};

ReservationsRecordTable.today = function () { // 点击上面状态筛选表格
    $("#startFilingTime").val(setDateTime(new Date(),0) + " " + "00:00:00");
    $("#endFilingTime").val(setDateTime(new Date(),0) + " " + "23:59:59");
    ReservationsRecordTable.search();
};

ReservationsRecordTable.yesterday = function () { // 昨天
    $("#startFilingTime").val(setDateTime(new Date(),1) + " " + "00:00:00");
    $("#endFilingTime").val(setDateTime(new Date(),1) + " " + "23:59:59");
    ReservationsRecordTable.search();
};

ReservationsRecordTable.thisWeek = function () { // 本周
    var date = new Date();
    var currentWeek = date.getDay();
    var stepSunDay = -currentWeek + 1;
    if (currentWeek == 0) {stepSunDay = -7;}
    var stepMonday = 7 - currentWeek;
    var time = date.getTime();
    var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
    var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
    $("#startFilingTime").val(setDateTime(monday,0) + " " + "00:00:00");
    $("#endFilingTime").val(setDateTime(sunday,0) + " " + "23:59:59");
    ReservationsRecordTable.search();
};

ReservationsRecordTable.thisMonth = function () { // 本月
    $("#startFilingTime").val(firstMonthTime(new Date(),0) + " " + "00:00:00");
    $("#endFilingTime").val(setMonthTime(new Date(),0) + " " + "23:59:59");
    ReservationsRecordTable.search();
};

ReservationsRecordTable.lastMonth = function () { // 上个月
    $("#startFilingTime").val(firstMonthTime(new Date(),1) + " " + "00:00:00");
    $("#endFilingTime").val(setMonthTime(new Date(),1) + " " + "23:59:59");
    ReservationsRecordTable.search();
};

$("#marketSearchAll", parent.document).click(function () { // 主页搜索
    ReservationsRecordTable.search();
});
function phonePrivileges(){   //隐藏手机号
    var phonePrivileges=parent.$("#phonePrivileges").val();
    if(phonePrivileges == 2){
        $('#ReservationsRecordTable').bootstrapTable('hideColumn', 'customerPhone');
    }
}

var scollPostion = 0;
ReservationsRecordTable.getScrollPosition = function (){ // 获取表格滚动到什么地方
    scollPostion = $('#ReservationsRecordTable').bootstrapTable('getScrollPosition');
};

ReservationsRecordTable.scrollTo = function (){ // 指定表格滚动到什么地方
    $("#ReservationsRecordTable").on('load-success.bs.table',function(data){
        $('#ReservationsRecordTable').bootstrapTable('scrollTo', scollPostion);
    });
};

$(function () {
    var defaultColunms = ReservationsRecordTable.initColumn();
    var table = new BSTable(ReservationsRecordTable.id, "/reservation/list2", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(ReservationsRecordTable.formParams());
    ReservationsRecordTable.table = table.init();
    ReservationsRecordTable.today();
    menuNameHideColumn($("#menuName").val(),'ReservationsRecordTable');
    $("#today").addClass('actionClick').siblings().removeClass('actionClick');
    $(document).on('click','#laydate_clear,#laydate_today,#laydate_ok',function () {ReservationsRecordTable.search();});
    $("#oneChannel").change(function () {$("#twoChannel").val('请选择');$("#thrChannel").val('请选择');ReservationsRecordTable.search();});
    $("#twoChannel").change(function () {$("#thrChannel").val('请选择');ReservationsRecordTable.search();});
    $("#thrChannel").change(function () {ReservationsRecordTable.search();});
    checkDate = function () {ReservationsRecordTable.search();};
    callbackTable = function () {ReservationsRecordTable.search();};
    phonePrivileges();
});